<?php

namespace app\api\controller;

use app\common\BaseHelper;

use app\admin\model\Flashsale as FlashsaleMdl;
use app\admin\model\Product;

class Flashsale extends Base
{
    /**
     * 获取限时特价商品列表
     */
    public function getList()
    {
        $param = self::getHttpParam();
        $start = 0;
        $length = 20;

        if (empty($param->time_range)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '时间段(time_range) 不能为空');
        }
        if (!in_array($param->time_range, [7, 10, 13, 16, 19])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '时间段(time_range) 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }
        $where = [
            'a.status' => 1,
            'a.start_time' => ['elt', date('Y-m-d H:i:s')],
            'a.end_time' => ['egt', date('Y-m-d H:i:s')],
            'a.effective_date' => ['like', '%,' . $param->time_range . ',%']
        ];

        $model = new FlashsaleMdl();
        $fields = 'a.product_id, a.ori_price, a.promotion_type, a.promotion_discount, a.buy_limit_type, a.buy_limit_num, a.start_time, a.end_time, a.effective_date, a.to_user_type, a.to_users, a.range, a.store_ids, b.id, b.name, b.img_url, b.price, b.unit, b.spec, b.describe, b.type';
        $order = 'a.create_date DESC';
        $list = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.product_id = b.id')->field($fields)->limit($start, $length)->order($order)->select();
        if (!$list) {
            return show(config('status.ERROR_STATUS'), '没有相关商品', '没有相关商品');
        }
        $total = $model->alias('a')->where($where)->join('__PRODUCT__ b', 'a.product_id = b.id')->count();

        $productMdl = new Product();
        $list = $productMdl->formatProducts($list);

        // 结束时间的时间戳
        $endTime = strtotime(date('Y-m-d') . ' ' . ($param->time_range + 2) . ':59:59');
        $data = [
            'list' => $list,
            'end_time' => $endTime
        ];

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data, $total);
    }
}